// CountPOAClient.java  Static Client, VisiBroker for Java
package Server2;

import org.omg.CosNaming.*;

import java.io.*;
import java.util.Random;

class CountPOAClient
{ 
	public static void main(String args[]) {
	final int totalIncrements = 10000;

	try
    { // Initialize the ORB
      System.out.println("Initializing the ORB");
      org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init(args, null);
      CounterPOA.Count counter=null;

      if(new File("ior.txt").exists())
	  {
	      try
		  {
		      BufferedReader b_In = new BufferedReader( new InputStreamReader( new FileInputStream("ior.txt")));
		      counter= CounterPOA.CountHelper.narrow(orb.string_to_object(b_In.readLine()));
		  }
	      catch(IOException IOe)
		  {
		      System.out.println("failed to read ior.txt");
		      System.exit(1);
		  }
	  }
      else
	  {
	      // Get a reference to the Naming service
	      org.omg.CORBA.Object nameServiceObj =
		  orb.resolve_initial_references ("NameService");
	      if (nameServiceObj == null)
		  {
		      System.out.println("nameServiceObj = null");
		      return;
		  }

	      org.omg.CosNaming.NamingContext nameService =
		  org.omg.CosNaming.NamingContextHelper.narrow (nameServiceObj);
	      if (nameService == null)
		  {
		      System.out.println("nameService = null");
		      return;
		  }

	      
	      CounterPOA.Count[] counterArray = new CounterPOA.Count[1000];
	      Random randomGen = new Random();
	      
	      for (int x = 0; x < 1000; x++) {
		      // resolve the Count object in the Naming service
		      NameComponent[] countName = {new NameComponent("countName".concat(String.valueOf(x+1)), "")};
		      counterArray[x] = CounterPOA.CountHelper.narrow(nameService.resolve(countName));
		      
		   // Set sum to initial value of 0
		      counterArray[x].sum((int)0);
	      }
	      
	      // Calculate Start time
	      long startTime = System.currentTimeMillis();

	      for (int i = 0; i < totalIncrements; i++) {
	    	  if (i % (totalIncrements/10) == 0)
	    		  System.out.println(i + "/" + totalIncrements + " done");
	    	  int rand = randomGen.nextInt(1000);
		      counterArray[rand].increment();
	      }
	      
	      // Calculate stop time; print out statistics
	      long stopTime = System.currentTimeMillis();
	      
	      System.out.println("Avg time to increment a counter = " + ((stopTime - startTime)/1000000f) + " msecs");
	      
	      int average = 0;
	      for (int x = 0; x < 1000; x++)
	    	  average += counterArray[x].sum();

    	  System.out.println("Average Sum: " + (double) average/1000f);	      
	  }

 
    } catch(Exception e)
    { System.err.println("Exception");
      System.err.println(e);
    }
  }
}
